package com.zzyl.common.ai;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AIModelInvoker {

    @Autowired
    private BaiduAIProperties baiduAIProperties;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 调用千帆大模型
     * @param prompt 用户输入的提示词
     * @return AI模型返回的结果
     */
    public String qianfanInvoker(String prompt) {
        try {
            System.out.println("[AI调用] prompt: " + prompt);

            // 构建请求头（完全按照示例代码格式）
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 注意：示例代码中 appid 是空的，但我们还是设置上
            headers.set("appid", baiduAIProperties.getAppId() != null ? baiduAIProperties.getAppId() : "");
            // Authorization 头格式必须严格匹配
            headers.set("Authorization", "Bearer " + baiduAIProperties.getAccessToken());

            // 构建请求体（完全按照示例代码格式）
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", baiduAIProperties.getModel());
            
            // messages 数组，按照示例格式
            requestBody.put("messages", List.of(
                Map.of("role", "user", "content", prompt)
            ));
            
            // web_search 配置，完全按照示例代码格式
            Map<String, Object> webSearch = new HashMap<>();
            webSearch.put("enable", false);  // 默认关闭，与示例一致
            webSearch.put("enable_citation", false);
            webSearch.put("enable_trace", false);
            requestBody.put("web_search", webSearch);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            System.out.println("[AI调用] 请求URL: " + baiduAIProperties.getApiUrl());
            System.out.println("[AI调用] 请求头: " + headers);
            System.out.println("[AI调用] 请求体: " + objectMapper.writeValueAsString(requestBody));

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                baiduAIProperties.getApiUrl(),
                HttpMethod.POST,
                entity,
                String.class
            );

            System.out.println("[AI调用] 响应状态: " + response.getStatusCode());
            System.out.println("[AI调用] 响应内容: " + response.getBody());

            // 解析响应
            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                if (responseBody == null || responseBody.trim().isEmpty()) {
                    throw new RuntimeException("百度千帆API返回空响应");
                }
                
                JsonNode jsonNode = objectMapper.readTree(responseBody);
                
                // 检查是否有错误
                if (jsonNode.has("error")) {
                    JsonNode error = jsonNode.get("error");
                    String errorMsg = error.has("message") ? error.get("message").asText() : "未知错误";
                    String errorCode = error.has("code") ? error.get("code").asText() : "未知错误码";
                    throw new RuntimeException("百度千帆API错误 [" + errorCode + "]: " + errorMsg);
                }
                
                // 解析正常响应
                JsonNode choices = jsonNode.get("choices");
                if (choices != null && choices.isArray() && choices.size() > 0) {
                    JsonNode message = choices.get(0).get("message");
                    if (message != null && message.has("content")) {
                        String result = message.get("content").asText();
                        System.out.println("[AI调用] AI响应原始内容: " + result);
                        
                        // 处理markdown代码块格式的响应
                        String cleanedResult = cleanMarkdownCodeBlock(result);
                        System.out.println("[AI调用] AI响应清理后: " + cleanedResult);
                        return cleanedResult;
                    }
                }
                
                // 如果没有 choices，检查是否有其他格式的响应
                if (jsonNode.has("result")) {
                    String result = jsonNode.get("result").asText();
                    String cleanedResult = cleanMarkdownCodeBlock(result);
                    System.out.println("[AI调用] AI响应成功(旧格式): " + cleanedResult);
                    return cleanedResult;
                }
                
                throw new RuntimeException("百度千帆API响应格式异常，未找到有效内容");
            } else {
                throw new RuntimeException("百度千帆API调用失败，响应状态: " + response.getStatusCode() + ", 响应内容: " + response.getBody());
            }
            
        } catch (Exception e) {
            System.err.println("[AI调用] 调用千帆大模型失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("AI分析失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 清理markdown代码块格式，提取纯JSON内容
     * @param content 原始内容
     * @return 清理后的JSON字符串
     */
    private String cleanMarkdownCodeBlock(String content) {
        if (content == null) {
            return null;
        }
        
        // 去除前后空白
        content = content.trim();
        
        // 检查是否以```json开头和```结尾
        if (content.startsWith("```json") && content.endsWith("```")) {
            // 移除开头的```json和结尾的```
            content = content.substring(7); // 移除"```json"
            content = content.substring(0, content.length() - 3); // 移除结尾的"```"
            content = content.trim();
        }
        // 检查是否以```开头和```结尾（没有指定语言）
        else if (content.startsWith("```") && content.endsWith("```")) {
            // 移除开头的```和结尾的```
            content = content.substring(3); // 移除开头的"```"
            content = content.substring(0, content.length() - 3); // 移除结尾的"```"
            content = content.trim();
        }
        
        return content;
    }
}
